package exam;

import java.util.Scanner;

public class Exam02 {
    public static void main(String[] args) {
        // 二分查找
        int[] nums = {-9, -1, 2, 3, 3, 4, 10};
        Scanner sc = new Scanner(System.in);
        int key = sc.nextInt();
        int index = binarySearch(nums, key, 0, nums.length - 1);
        System.out.println(key + "在数组中的下标是：" + index);
    }

    // 定义一个方法实现 二分查找 传递数组 和要查找的值 如果存在 返回下标  不存在返回 -1
    public static int binarySearch(int[] arr, int key) {
        int start = 0;
        int end = arr.length - 1;
        while (start <= end) {
            int mid = (start + end) / 2;  // 中间的下标
            if (arr[mid] == key) {
                return mid;
            } else if (arr[mid] > key) {
                end = mid - 1;
            } else {
                start = mid + 1;
            }
        }
        return -1;
    }

    public static int binarySearch(int[] arr, int key, int start, int end) {
        if (start > end) {
            return -1;
        }
        int mid = (start + end) / 2;  // 中间的下标
        if (arr[mid] == key) {
            return mid;
        } else if (arr[mid] > key) {
            return binarySearch(arr, key, start, mid - 1);
        } else {
            return binarySearch(arr, key, mid + 1, end);
        }
    }

}
